package com.tubemostwanted.model;

import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.tubemostwanted.entity.Category;

public class CategoryModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();

	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Category> all() {
		initPm();
		List<Category> result = new ArrayList<Category>();
		Query query = pm.newQuery(Category.class);
		query.setFilter("status==1");
		query.setOrdering("index asc");
		result = (List<Category>) query.execute();
		return result;
	}

	@SuppressWarnings("unchecked")
	public static List<Category> getTop4() {
		initPm();
		List<Category> result = new ArrayList<Category>();
		Query query = pm.newQuery(Category.class);
		query.setFilter("status==1");
		query.setOrdering("index asc");
		query.setRange(0, 4);
		result = (List<Category>) query.execute();
		return result;
	}

	public static boolean add(Category cate) {
		initPm();
		try {
			pm.makePersistent(cate);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Category> listCate) {
		initPm();
		try {
			pm.makePersistentAll(listCate);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Category cate) {
		initPm();
		pm.makePersistent(cate);
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Category getByCateAlias(String alias) {
		initPm();
		Category cate = null;
		Query query = pm.newQuery(Category.class);
		query.setFilter("alias=='" + alias + "' && status==1");
		query.setRange(0, 1);
		List<Category> listResult = (List<Category>) query.execute(alias);
		if (listResult.size() > 0) {
			cate = listResult.get(0);
		}
		return cate;
	}

	@SuppressWarnings("unchecked")
	public static long getMaxIndex() {
		initPm();
		try {
			Query query = pm.newQuery(Category.class);
			query.setFilter("status==1");
			query.setOrdering("index desc");
			List<Category> listResult = (List<Category>) query.execute();
			if (listResult != null && listResult.size() > 0) {
				return listResult.get(0).getIndex();
			} else {
				return 0;
			}
		} catch (Exception e) {
			return 0;
		}		
	}

	public static void closePM() {
		pm.close();
	}

}
